<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div class="filter-item">
        <el-form :inline="true" :model="queryParams" size="small">
          <el-form-item label="流程名称">
            <el-input v-model="queryParams.name" placeholder="请输入流程名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="list-container">
      <div class="action-container">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增流程</el-button>
      </div>

      <el-table v-loading="loading" :data="flowList" border>
        <el-table-column label="流程名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="创建人" prop="creatorName" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleToggleStatus(scope.row)"
            >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getList"
      />
    </el-card>

    <!-- 查看流程对话框 -->
    <el-dialog title="查看审批流程" :visible.sync="viewDialogVisible" width="70%">
      <div class="flow-view">
        <h3>{{ viewForm.name }}</h3>
        <p class="flow-description">{{ viewForm.description }}</p>
        <div class="flow-nodes">
          <el-steps direction="vertical" :active="viewForm.nodes ? viewForm.nodes.length : 0">
            <el-step 
              v-for="(node, index) in viewForm.nodes" 
              :key="index" 
              :title="'节点 ' + (index + 1)" 
              :description="node.approverName + ' (' + node.approverDepartment + ')'"
            ></el-step>
          </el-steps>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑流程对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="70%">
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="流程描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="editForm.description" 
            placeholder="请输入流程描述" 
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="审批节点">
          <el-button type="primary" size="small" @click="addNode">添加节点</el-button>
          <div class="node-list">
            <div v-for="(node, index) in editForm.nodes" :key="index" class="node-item">
              <el-card>
                <div slot="header" class="clearfix">
                  <span>节点 {{ index + 1 }}</span>
                  <el-button 
                    style="float: right; padding: 3px 0" 
                    type="text" 
                    icon="el-icon-delete"
                    @click="removeNode(index)"
                  ></el-button>
                </div>
                <el-form-item 
                  :label="'审批人'"
                  :prop="'nodes.' + index + '.approverId'"
                  :rules="{ required: true, message: '请选择审批人', trigger: 'change' }"
                >
                  <el-select 
                    v-model="node.approverId" 
                    filterable 
                    remote 
                    reserve-keyword
                    placeholder="请输入关键词搜索"
                    :remote-method="remoteSearchUsers"
                    :loading="loading"
                    style="width: 100%"
                    @change="handleApproverChange($event, index)"
                  >
                    <el-option
                      v-for="item in userOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-card>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFlowList, getFlowDetail, createFlow, updateFlow, deleteFlow, toggleFlowStatus } from '@/api/flow'
import { searchUsers } from '@/api/user'
import Pagination from '@/components/Pagination'

export default {
  name: 'ApprovalFlow',
  components: { Pagination },
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        name: undefined
      },
      // 流程列表
      flowList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 用户选项
      userOptions: [],
      // 查看对话框
      viewDialogVisible: false,
      viewForm: {},
      // 编辑对话框
      editDialogVisible: false,
      dialogTitle: '',
      editForm: {
        id: undefined,
        name: '',
        description: '',
        status: 1,
        nodes: []
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取流程列表
    getList() {
      this.loading = true
      getFlowList(this.queryParams).then(response => {
        this.flowList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 查询按钮
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        name: undefined
      }
      this.getList()
    },
    // 格式化时间
    formatDateTime(datetime) {
      if (!datetime) return ''
      const date = new Date(datetime)
      return date.toLocaleString()
    },
    // 新增按钮
    handleAdd() {
      this.dialogTitle = '新增审批流程'
      this.editForm = {
        id: undefined,
        name: '',
        description: '',
        status: 1,
        nodes: []
      }
      this.editDialogVisible = true
    },
    // 查看按钮
    handleView(row) {
      getFlowDetail(row.id).then(response => {
        this.viewForm = response.data
        this.viewDialogVisible = true
      })
    },
    // 编辑按钮
    handleEdit(row) {
      getFlowDetail(row.id).then(response => {
        this.editForm = response.data
        this.dialogTitle = '编辑审批流程'
        this.editDialogVisible = true
      })
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该审批流程吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFlow(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 切换状态
    handleToggleStatus(row) {
      const statusText = row.status === 1 ? '禁用' : '启用'
      this.$confirm(`确认${statusText}该审批流程吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        toggleFlowStatus(row.id).then(() => {
          this.$message.success(`${statusText}成功`)
          this.getList()
        })
      }).catch(() => {})
    },
    // 添加节点
    addNode() {
      this.editForm.nodes.push({
        approverId: undefined,
        approverName: '',
        approverDepartment: '',
        orderNum: this.editForm.nodes.length + 1
      })
    },
    // 删除节点
    removeNode(index) {
      this.editForm.nodes.splice(index, 1)
      // 重新排序
      this.editForm.nodes.forEach((node, idx) => {
        node.orderNum = idx + 1
      })
    },
    // 远程搜索用户
    remoteSearchUsers(query) {
      if (query !== '') {
        this.loading = true
        searchUsers({ keyword: query }).then(response => {
          this.userOptions = response.data.map(item => {
            return { 
              value: item.id, 
              label: item.name + ' (' + item.username + ')',
              department: item.departmentName
            }
          })
          this.loading = false
        })
      } else {
        this.userOptions = []
      }
    },
    // 审批人变更
    handleApproverChange(value, index) {
      const selectedUser = this.userOptions.find(item => item.value === value)
      if (selectedUser) {
        this.editForm.nodes[index].approverName = selectedUser.label.split(' ')[0]
        this.editForm.nodes[index].approverDepartment = selectedUser.department
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.editForm.nodes.length === 0) {
            this.$message.warning('请至少添加一个审批节点')
            return
          }
          
          const method = this.editForm.id ? updateFlow : createFlow
          method(this.editForm).then(() => {
            this.$message.success('保存成功')
            this.editDialogVisible = false
            this.getList()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.action-container {
  margin-bottom: 20px;
}
.flow-view {
  padding: 20px;
}
.flow-view h3 {
  text-align: center;
  margin-bottom: 10px;
}
.flow-description {
  text-align: center;
  color: #606266;
  margin-bottom: 30px;
}
.flow-nodes {
  padding: 20px;
}
.node-list {
  margin-top: 15px;
}
.node-item {
  margin-bottom: 15px;
}
</style> 